﻿using Demo.Net.MongoDB;
using Microsoft.Extensions.Options;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace Demo.Net.MongoDB
{
    internal class MongoClientFactory: IMongoClientFactory
    {

        private readonly IOptionsMonitor<MongoClientOption> _optionsMonitor;

        public MongoClientFactory(IOptionsMonitor<MongoClientOption> optionsMonitor)
        {
            _optionsMonitor = optionsMonitor ?? throw new ArgumentNullException(nameof(optionsMonitor));
        }


        public IMongoDatabase Get(string dbname)
        {
            var options = _optionsMonitor.Get(dbname);

            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            if (options.MongoDatabase == null)
            {
                lock (dbname)
                {
                    var mongoUrl = new MongoUrlBuilder(options.ConnectionString)
                    {
                        //数据库名称，如果连接字符串不指定
                        DatabaseName = dbname,
                        //MaxConnectionPoolSize = 20000, //最大链接数
                        //当客户端和服务器之间的连接一段时间没有活动时，服务器会将连接标记为"空闲"状态，并在一段时间后自动关闭连接。
                        MaxConnectionIdleTime = TimeSpan.FromSeconds(120),
                        //队列等待时间
                        WaitQueueTimeout = TimeSpan.FromSeconds(10),
                        //最大存活时间
                        MaxConnectionLifeTime = TimeSpan.FromSeconds(60 * 2)

                    };
                    //获取数据库名称
                    var databaseName = mongoUrl.DatabaseName;
                    var mongoClient = new MongoClient(mongoUrl.ToMongoUrl());
                    return mongoClient.GetDatabase(databaseName); 
                }
            }

            return options.MongoDatabase;
        }
    }
}
